"use client";
import React, { useEffect, useMemo, useState } from "react";
import { useDrag } from "@use-gesture/react";
import { animated } from "@react-spring/web";
interface IProps {
    onSwipe?: (dir: "left" | "right") => void;
    children?: React.ReactNode[];
    threshold?: number;
    velocity?: number;
    scale?: number;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    data: any[];
    active?: number;
    render?: (index: number) => React.ReactNode;
}

export const Swipeable: React.FC<IProps> = ({
    onSwipe,
    render = (e) => e,
    data = [0, 1, 2, 3, 4, 5],
    active = 0,
}) => {
    const [_active, set_active] = useState(0);
    useEffect(() => {
        set_active(active);
    }, [active]);
    const showList = useMemo(() => {
        const prev = Math.max(_active - 1, 0);
        const next = Math.min(_active + 1, data.length - 1);
        const result = data.slice(prev, next + 1);

        return result.map((e) => (
            <div key={e.id} className="w-full h-full flex-shrink-0">
                {render(e)}
            </div>
        ));
    }, [_active, data, render]);
    const invokeSwipe = (dir: Parameters<Required<IProps>["onSwipe"][0]>) => {
        if (dir === "left") {
            set_active(Math.min(_active + 1, data.length - 1));
            onSwipe?.(dir);
        }
        if (dir === "right") {
            set_active(Math.max(_active - 1, 0));
            onSwipe?.(dir);
        }
    };
    const w = 0;
    const bind = useDrag(
        (e) => {
            const {
                direction: [dx],
                movement: [mx],
                velocity: [vx],
                currentTarget,
                cancel,
                canceled,
                _active,
            } = e;
            if (!_active || canceled) {
                return;
            }
            const w = (currentTarget as HTMLElement).clientWidth;

            const td = Math.min(w / 3, 100);

            if (Math.abs(mx) < td || Math.abs(vx) < 0.3) {
                return;
            }
            invokeSwipe?.(dx > 0 ? "right" : "left");
            cancel();
        },
        {
            axis: "x",
            preventScroll: true,
            trackTouch: true,
            filterTaps: true,
            pointer: {
                touch: true,
            },
        }
    );

    return (
        <>
            <div>{_active}</div>
            <div className="w-full h-full" {...bind()}>
                <animated.div
                    style={{
                        x: _active == 0 ? 0 : -w,
                    }}
                    className="w-full h-full flex flex-nowrap touch-pan-y"
                >
                    {showList}
                </animated.div>
            </div>
        </>
    );
};
